<?php

namespace App\Service;

use App\Model\ChatgptMessage;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class ChatGptService extends BaseService
{


    /**
     * @Inject()
     * @var HttpService
     */
    private $httpService;


    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;


    /**
     * chatGPT发送消息
     * @param $user
     * @param string $message
     * @param $uid
     * @param int $type
     * @return array
     */
    public function sendMessage($user, $message = '', $uid, $type = 1)
    {

        //测试环境下 没法调用 就直接返回结果
        if ($this->dev()) {

            $url = "https://api.seekingaround.com/api/v1/test/chatGptTest";
            $options['headers'] = [
                'Content-Type' => 'application/json',
            ];
            $json['content'] = $message;
            $options['json'] = $json;
        } else {

            $url = "https://api.openai.com/v1/chat/completions";

            $options['headers'] = [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer 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',
                'OpenAI-Organization' => 'org-RVbHPn3yThVrDrJHkSybQXqf',
            ];


            $json['model'] = 'gpt-3.5-turbo';
            $json['messages'] = [[
                'role' => 'user',
                'content' => $message ?? 'hello',
                'user' => $user
            ]];
            $options['json'] = $json;

        }
        // 临时做中转
        $result = $this->httpService->request($url, $options, 'POST');
        if ($result) {

            if (isset($result['choices'][0])) {

                $content = $result['choices'][0]['message']['content'];


                $insertData = [
                    'uid' => $uid,
                    'send' => $message,
                    'reply' => $content,
                    'create_time' => time(),
                    'type' => $type
                ];

                ChatgptMessage::insert($insertData);


                return ['code' => 200, 'message' => $content];
            } else {
                recordExceptionLog('chatGPT请求报错', json_encode($result));
                return ['code' => 0, 'message' => 'error'];
            }

        } else {
            recordExceptionLog('chatGPT请求报错', json_encode($result));
            return ['code' => 0, 'message' => 'error'];
        }


    }







    public function dev()
    {

        $env = env('APP_ENV', 'dev');

        if ($env) {
            return true;
        } else {
            return false;
        }

    }


}
